package cn.maiyar.web;

import cn.hutool.core.util.StrUtil;
import cn.maiyar.common.api.Result;
import cn.maiyar.common.api.ResultCode;
import cn.maiyar.common.constant.CommonConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 控制器基类
 *
 * @author c.c
 */
public abstract class BaseController {

    @Value("${spring.profiles.active}")
    protected String active;

    @Resource
    private MessageSource messageSource;

    /**
     * 是否是开发和测试环境
     *
     * @return
     */
    protected boolean isDevEnv() {
        return active.startsWith(CommonConstant.DEV_CODE) || active.startsWith(CommonConstant.BETA_CODE);
    }

    /**
     * 多语言信息
     *
     * @return
     */
    protected String locale() {
        String languageTag = LocaleContextHolder.getLocale().toLanguageTag();
        return StrUtil.isBlank(languageTag) ? "zh-cn" : languageTag.toLowerCase();
    }


    /**
     * 返回request
     *
     * @return
     */
    private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 获取客户端的版本名称
     *
     * @return
     */
    protected String getVersionName() {
        String versionName = getRequest().getHeader("Version-Name");
        if (StrUtil.isEmpty(versionName)) {
            versionName = getRequest().getParameter("Version-Name");
        }
        return StrUtil.isEmpty(versionName) ? "0.0.1" : versionName;
    }

    /**
     * 获取客户端的版本数字号
     *
     * @return
     */
    protected Integer getVersionCode() {
        String versionCode = getRequest().getHeader("Version-Code");
        if (StrUtil.isEmpty(versionCode)) {
            versionCode = getRequest().getParameter("Version-Code");
        }
        return StrUtil.isEmpty(versionCode) ? 1 : Integer.parseInt(versionCode);
    }

    /**
     * 返回错误代码和对应的错误消息
     *
     * @param code   错误代码
     * @param params 错误消息格式化需要的参数
     * @return JsonViewData对象
     */
    protected Result error(String code, Object... params) {
        String message = messageSource.getMessage(String.valueOf(code), null, LocaleContextHolder.getLocale());
        if (params != null && params.length > 0) {
            message = String.format(message, params);
        }
        if (StrUtil.isEmpty(message)) {
            message = ResultCode.SYSTEM_RESOURCE_ERROR.getMessage();
        }
        return Result.fail(code, message);
    }
}
